<template>
  <div
    style="position: relative; width: 100vw; height: 700px; top: 60px"
    :style="{ height: styleHeight + 'px', top: !mobile ? '60px' : '0' }"
  >
    <el-card v-if="!resShow" class="card" :style="{ width: cardWidth + '%' }">
      <!-- <template #header>
                <div class="card-header">
                    <el-page-header @back="goBack" style="color: #ecf5ff">
                        <template #content><span class="text-large font-600 mr-3" style="color: #ecf5ff">
                                建设单位注册
                            </span></template>
                    </el-page-header>
                    <el-button style="color: #18585" type="success" text @click.prevent="clearUp">清空</el-button>
                </div>
            </template> -->
      <div class="div-msg">
        提示：检测到当前账号未完善建设单位信息，且密码为弱口令，请进行完善相关信息后进入操作页面！
      </div>
      <div :style="{ height: styleHeight - 100 + 'px' }" style="overflow-y: auto">
        <el-form
          ref="constructorFormRef"
          v-loading="loading"
          :element-loading-text="loadingText"
          :model="constructorForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
        >
          <!-- 数据部分 -->
          <!-- <div class="div_row"> -->
          <el-row>
            <el-col :span="itemSpan">
              <el-form-item label="建设单位名称" prop="name">
                <el-input
                  v-model="constructorForm.name"
                  :disabled="true"
                  placeholder="请输入建设单位名称、个人姓名"
                  class="input300"
                />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="建设信用代码" prop="code">
                <el-input
                  v-model="constructorForm.code"
                  placeholder="请输入建设信用代码、身份证号码"
                  class="input300"
                />
              </el-form-item>
            </el-col>
            <!--        </el-row>-->
            <!--        <el-row>-->
            <el-col :span="itemSpan">
              <el-form-item label="法人姓名" prop="legalman">
                <el-input v-model="constructorForm.legalman" placeholder="请输入法人姓名" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="法人身份证号码" prop="legalCardno">
                <el-input v-model="constructorForm.legalCardno" placeholder="请输入法人身份证号码" class="input300" />
              </el-form-item>
            </el-col>
            <!--        </el-row>-->
            <!--        <el-row>-->
            <el-col :span="itemSpan">
              <el-form-item label="法人手机号码" prop="legalMobile">
                <el-input v-model="constructorForm.legalMobile" placeholder="请输入法人手机号码" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="联系人名称" prop="linkMan">
                <el-input v-model="constructorForm.linkMan" placeholder="请输入联系人名称" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="联系人电话" prop="linkTel">
                <el-input v-model="constructorForm.linkTel" placeholder="请输入联系人手机号码" class="input300" />
                <el-button
                  type="success"
                  style="position: absolute; right: -50px"
                  plain
                  :disabled="disCode"
                  @click="tryCode"
                  >{{ codeBtn }}</el-button
                >
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="验证码" prop="verificationCode">
                <el-input v-model="constructorForm.verificationCode" placeholder="请输入验证码" class="input300" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="归属地区" prop="areaCode">
                <el-cascader
                  v-model="constructorForm.areaCode"
                  placeholder="请选择归属地区"
                  :options="areaoptions"
                  @change="handleCascaderChange"
                />
              </el-form-item>
            </el-col>
            <!--        </el-row>-->

            <!--        <el-col :span="mobile ? itemSpan : 22">-->
            <el-col :span="22">
              <el-form-item label="注册地址" prop="regAddr">
                <el-input v-model="constructorForm.regAddr" placeholder="请输入注册地址" />
              </el-form-item>
            </el-col>
            <!--        <el-col :span="mobile ? itemSpan : 22">-->
            <el-col :span="22">
              <el-form-item label="办公地址" prop="officeAddr">
                <el-input v-model="constructorForm.officeAddr" placeholder="请输入办公地址" />
              </el-form-item>
            </el-col>
            <!--        <el-row>-->
            <el-col :span="itemSpan">
              <el-form-item label="建设单位类型">
                <el-select v-model="constructorForm.type" placeholder="请选择建设单位类型" class="input300" clearable>
                  <el-option
                    v-for="item in constructorType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label=""> </el-form-item>
            </el-col>
            <!--        </el-row>-->
            <!--        <el-row>-->
            <el-col :span="itemSpan">
              <el-form-item label="登录密码" prop="password">
                <!-- <el-input
                  v-model="constructorForm.password"
                  type="password"
                  placeholder="请输入登录密码"
                  class="input300"
                /> -->

                <PasswordInput ref="passwordInputRef" class="input300" @input-change="handlePasswordChange" />
              </el-form-item>
            </el-col>
            <el-col :span="itemSpan">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="constructorForm.confirmPassword"
                  type="password"
                  placeholder="请输入确认密码"
                  class="input300"
                  :show-password="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24" style="display: flex; align-item: center; justify-content: center">
            <el-button type="primary" :loading="loading" style="width: 100px; margin-top: 30px" @click.prevent="submit">
              下一步
            </el-button>
            <!-- <el-button @click.prevent="resetFields">清空</el-button> -->
          </el-col>
          <!-- </div> -->
        </el-form>
      </div>
    </el-card>
    <resComponent v-else style="margin-top: 200px"></resComponent>
  </div>
</template>

<script lang="ts" setup>
import { constructorReg, getConstructorInfo, constructorLogin } from "@/api/account/constructor/index";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ConstructorForm } from "@/api/account/constructor/types";
import { getVerificationCode } from "@/api/account/project/index";
import { getDicts } from "@/store/modules/dict";
import { LocationQuery, LocationQueryValue, useRouter, useRoute } from "vue-router";
import resComponent from "@/views/account/register/resComponent/index.vue";
import PasswordInput from "@/components/PasswordInput/index.vue";
import { isMobile } from "@/utils";
import { useScreen } from "@/store/modules/screen";
import { useAppStore } from "@/store/modules/app";

const codeBtn = ref("获取验证码");
const codeCount = ref(60);
const disCode = ref(false);
const screenStore = useScreen();
const appStore = useAppStore();
const router = useRouter();
const loading = ref(false);
const loadingText = ref("");
const resShow = ref(false);
const itemSpan = ref(12);
const mobile = ref(false);
const styleHeight = ref(600);
const cardWidth = ref(50);
const route = useRoute();
let codeInterval = ref();
if (isMobile()) {
  mobile.value = true;
  itemSpan.value = 24;
  styleHeight.value = screenStore.screenHeight;
  cardWidth.value = 100;
} else {
  styleHeight.value = 700;
  cardWidth.value = 50;
}

const constructorForm = reactive<ConstructorForm>({
  type: 10,
  confirmPassword: "",
  password: "",
});
const allowPassword = ref(false);
const handlePasswordChange = (value: any, allow: boolean) => {
  constructorForm.password = value;
  allowPassword.value = allow;
};
const constructorFormRef = ref(ElForm); // 表单/清空重置使用
//城市联动赋值
const handleCascaderChange = (value: any) => {
  if (value.length == 3) {
    constructorForm.provinceCode = value[0];
    constructorForm.cityCode = value[1];
    constructorForm.areaCode = value[2];
  }
  // 在这里可以对选中的值进行进一步处理
};
//枚举
const constructorType = getDicts("constructorTypes");
const areaoptions = getDicts("areaTrees");

const rules = reactive<FormRules<ConstructorForm>>({
  name: [{ required: true, message: "建设单位名称不能为空", trigger: "blur" }],
  code: [{ required: true, trigger: "blur", validator: codeBlur }],
  password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }],
  // provinceCode: [{ required: true, message: "归属省不能为空", trigger: "blur" }],
  cityCode: [{ required: true, message: "归属地市不能为空", trigger: "blur" }],
  // areaCode: [{ required: true, message: "归属区县不能为空", trigger: "blur" }],
  regAddr: [{ required: true, message: "注册地址不能为空", trigger: "blur" }],
  officeAddr: [{ required: true, message: "办公地址不能为空", trigger: "blur" }],
  legalman: [{ required: true, message: "法人姓名不能为空", trigger: "blur" }],
  legalCardno: [
    { required: true, message: "法人身份证号码不能为空", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号码",
      trigger: "blur",
    },
  ],
  legalMobile: [
    { required: true, message: "法人手机号码不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  linkMan: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  linkTel: [
    { required: true, message: "联系人电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  confirmPassword: [{ required: true, trigger: "blur", validator: passwordBlur }],
});
onMounted(() => {
  initForm();
});
//返回上一页
const goBack = () => {
  router.go(-1);
};
function tryCode() {
  if (!constructorForm.linkTel) {
    ElMessage.warning("请输入手机号码");
    return;
  }
  let reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (!reg.test(constructorForm.linkTel)) {
    ElMessage.warning("请输入正确的手机号码");
    return;
  }
  getCode();
}

const getCode = useThrottleFn(async () => {
  btnToDis();
  let code = await getVerificationCode(constructorForm.linkTel ?? "");
  if (code.success) {
    ElMessage.success("验证码发送成功!");
  } else {
    ElMessage.error(code.msg);
    disCode.value = false;
    codeCount.value = 60;
    codeBtn.value = "获取验证码";
    clearInterval(codeInterval.value);
  }
}, 3000);

function btnToDis() {
  disCode.value = true;
  codeInterval.value = setInterval(() => {
    if (codeCount.value > 0) {
      codeCount.value--;
      codeBtn.value = `重新获取 (${codeCount.value})`;
    } else {
      disCode.value = false;
      codeCount.value = 60;
      codeBtn.value = "获取验证码";
      clearInterval(codeInterval.value);
    }
  }, 1000);
}

function initForm() {
  getConstructorInfo(route.query.editToken).then((res) => {
    if (res.success === true) {
      constructorForm.editToken = route.query.editToken;
      Object.assign(constructorForm, res.data);
    }
  });
}

function clearUp() {
  ElMessage.success("清空成功");
  constructorFormRef.value.resetFields();
  constructorFormRef.value.clearValidate();
}

function passwordBlur(rule: any, value: any, callback: any) {
  if (value === undefined || value === "") {
    callback(new Error("确认密码不能为空"));
  } else {
    if (value != constructorForm.password) {
      callback(new Error("两次密码不一致"));
    } else {
      callback();
    }
  }
}
function codeBlur(rule: any, value: any, callback: any) {
  if (!value || value === undefined || value === "") {
    callback(new Error("建设信用代码不能为空"));
    return;
  }
  if (value.length < 18) {
    callback(new Error("建设信用代码为18位"));
    return;
  } else {
    callback();
  }
}
const token = useStorage("accessToken", "");
/**
 * 表单提交
 */
const submit = useThrottleFn(() => {
  if (!allowPassword.value) {
    return;
  }
  constructorFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      constructorLogin(constructorForm)
        .then((data: any) => {
          if (data.success) {
            const { tokenType, accessToken } = data.data;
            token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx.
            resShow.value = true;
            loading.value = false;
            // setTimeout(() => {
            //   loading.value = false;
            //   router.push({ path: "dashboard" }).then(() => {
            //     ElMessage.success("登录成功");
            //   });
            // }, 3000);
          } else {
            ElMessage({
              type: "error",
              message: data.msg,
            });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

function resetFields() {
  ElMessage.success("清空成功");
  constructorFormRef.value.resetFields();
  constructorFormRef.value.clearValidate();
}
</script>
<style lang="scss" scoped>
.div_form {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.div_row {
  position: absolute;
  left: 0;
  right: 0;
  // top: 0;
  // bottom: 0;
  // margin: auto;
}

.card {
  width: 50%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  background-color: #337ecc;
  align-items: center;
  padding: 10px;
}

:deep() .el-card__header {
  padding: 0px;
}

.demo-ruleForm {
  width: 100%;
  padding-top: 20px;
  position: relative;
}

.div-felx {
  display: flex;
  justify-content: center;
}

.input300 {
  width: 80% !important;
}

.el-select .el-input__inner {
  width: 80% !important;
}

.date-picker {
  width: 80% !important;
}

.el-input__wrapper {
  width: 80% !important;
}

.custom-cascader {
  width: 80% !important;
}

:deep() .el-cascader {
  width: 80% !important;
}

.div-msg {
  text-align: center;
  margin: auto;
  line-height: 48px;
  color: red;
  font-size: 16px;
}
</style>
